<template>
  <div>
    <CategorySelector :isDisabled="!isShowAttrList" ></CategorySelector>
    <el-card>
      <div v-if="isShowAttrList">
        <el-button type="primary" :disabled="!categoryStore.category3Id" :icon="Plus" @click="toAddAttr">添加属性</el-button>
        <el-table border v-loading="loading" :data="attrList" style="margin-top:10px">
          <el-table-column label="序号" type="index" align="center" width="100px" />
          <el-table-column label="属性名称" prop="attrName" width="200px" />
          <el-table-column label="属性值列表">
            <template v-slot="{row}">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" style="margin-right:6px">{{attrValue.valueName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row,$index}">
              <el-tooltip class="box-item" effect="dark" content="修改属性" placement="top">
                <el-button type="warning" size="small" :icon="Edit" @click="toEditAttr(row)"></el-button>
              </el-tooltip>

              <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" title="真的要删除此属性吗?" @confirm="confirmEvent(row,$index)">
                <template #reference>
                  <div style="display: inline-block;margin-left:10px">
                    <el-tooltip class="box-item" effect="dark" content="删除属性" placement="top">
                      <el-button type="danger" size="small" :icon="Delete"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div v-else>
        <el-form :model="attrInfo">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" style="width:220px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Plus" :disabled="!attrInfo.attrName" @click="toAddAttrValue"> 添加属性值</el-button>
            <el-button type="default" @click="isShowAttrList=true">取消</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="attrInfo.attrValueList" style="margin-bottom:10px">
          <el-table-column label="序号" type="index" width="100px" align="center"></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{row,$index}">
              <el-input ref="inputRef" size="small" v-model="row.valueName" v-if="row.isShowInput" @blur="toDeleteCurrentRow(row,$index)"></el-input>
              <span v-else style="display:inline-block;width:100%" @dblclick="toEditAttrValue(row)">{{ row.valueName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row,$index}">
              <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" title="真的要删除此属性值吗?" @confirm="toDeleteAttrValue($index)">
                <template #reference>
                  <div style="display: inline-block;margin-left:10px">
                    <el-tooltip class="box-item" effect="dark" content="删除属性值" placement="top">
                      <el-button type="danger" size="small" :icon="Delete"></el-button>
                    </el-tooltip>
                  </div>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="toSaveAttrInfo">保存</el-button>
        <el-button @click="isShowAttrList=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'Attr'
});
</script>
<script lang="ts" setup>
import { ref, watch, reactive, nextTick } from 'vue';
import { Plus, Edit, Delete, InfoFilled } from '@element-plus/icons-vue';
// 在此语法糖当中，引入组件即注册
import CategorySelector from '@/components/CategorySeletor/index.vue';
import { useCategoryListStore } from '@/stores/categorySelector';
import { reqGetAttrListData, reqDeleteAttr, reqSaveOrUpdateAttrInfo } from '@/api/product/attr';
import { ElMessage } from 'element-plus';
import type { AttrInfoModel, AttrListModel, AttrValueModel } from '@/api/product/interface/attrModel';
const categoryStore = useCategoryListStore();
const isShowAttrList = ref<Boolean>(true);
const loading = ref<Boolean>(false);
const attrList = ref<AttrListModel>([]);
const inputRef = ref();
// 添加属性时需要收集的数据
const attrInfo = reactive<AttrInfoModel>({
  attrName: '',
  attrValueList: [],
  categoryId: 0,
  categoryLevel: 3
});

// 1. 根据一二三级导航id 获取属性列表数据
const getAttrListData = async () => {
  loading.value = true;
  const result = await reqGetAttrListData({ category1Id: categoryStore.category1Id, category2Id: categoryStore.category2Id, category3Id: categoryStore.category3Id });
  // console.log('rr', result);
  loading.value = false;
  attrList.value = result;
};

// 2. 当三级分类一选中的时候 就要获取数据
watch(
  () => categoryStore.category3Id,
  async (newVal, oldVal) => {
    // console.log('vv',newVal,oldVal)
    // if(newVal===undefined)
    // if (!newVal) {
    //   // if小括号中一般是boolean类型的值 如果不是boolean类型的值 小括号内部底层会自动调用Boolean函数将数据转换成boolean类型进行判断
    //   attrList.value = [] // 清空之前的旧值
    //   return; // 阻止代码向下执行
    // }

    // if (!newVal) {
    //   return attrList.value = [] // 清空之前的旧值
    // }

    if (!newVal) return (attrList.value = []);
    // 才要发送请求
    getAttrListData();
  },{immediate:true}
);


// 3. 删除属性
const confirmEvent = async (row:AttrInfoModel, index:number) => {
  // console.log('aaa',index)
  await reqDeleteAttr(row.id as number);

  ElMessage.success('删除属性成功...');

  // attrList.value.splice(index,1)
  // 重新发送请求 获取剩余的属性列表数据
  getAttrListData();
};

// 4. 收集属性值 也就是去添加属性值
const toAddAttrValue = () => {
  attrInfo.attrValueList.push({
    valueName: '',
    isShowInput: true // 是否显示输入框
  });

  // 获取焦点
  nextTick(() => {
    // 当页面的数据更新渲染完毕之后才会执行
    inputRef.value?.focus();
  });
};

// 5. 当输入框没有数据时 失去焦点要自删当前项
const toDeleteCurrentRow = (row:AttrValueModel, index:number) => {
  // if (!row.valueName) {
  //   attrInfo.attrValueList.splice(index, 1)
  //   return // 阻止代码向下执行
  // }

  // if (!row.valueName) {
  //   return attrInfo.attrValueList.splice(index, 1);
  // }

  if (!row.valueName) return attrInfo.attrValueList.splice(index, 1);

  // 如果当前输入框输入了值 在失去焦点后应该要显示span标签 而隐藏输入框
  row.isShowInput = false;
};
// 6. 去编辑当前属性值
const toEditAttrValue = (row:AttrValueModel) => {
  // 6.1 要显示输入框
  row.isShowInput = true;

  // 获取焦点
  nextTick(() => {
    // 当页面的数据更新渲染完毕之后才会执行
    inputRef.value?.focus();
  });
};
// 7. 删除某属性值
const toDeleteAttrValue = ( index:number) => {
  attrInfo.attrValueList.splice(index, 1);
};

// 8. 去添加属性
const toAddAttr = () => {
  attrInfo.attrName = ''
  attrInfo.attrValueList = []
  isShowAttrList.value = false

  // 删除属性的id
  delete attrInfo.id
}

// 9. 添加或更新平台属性  添加或是更新平台属性用的是同一个接口
const toSaveAttrInfo = async () => {
  attrInfo.categoryId = categoryStore.category3Id as number
  await reqSaveOrUpdateAttrInfo(attrInfo)
  ElMessage.success(`${attrInfo.id?'更新':'添加'}平台属性成功了...`)
  isShowAttrList.value = true 
  getAttrListData() // 重新获取一下数据
}

// 10. 更新属性之数据回显
const toEditAttr = (row:AttrInfoModel) => {
  Object.assign(attrInfo, row)
  isShowAttrList.value = false
};
</script>

<style scoped>
</style>